#!/bin/bash
cd ~
printf "\natv4me Link Web Interfaces v1.0\n"
printf "============================================================\n\n"
if [ "$(whoami)" != "root" ]; then
	echo "   [*] You do not have sufficient privileges to run this script."
	echo "   [*] Please run 'sudo -s' before running this script."
	printf "\n============================================================\n\n"
	exit
fi
### SET VARIABLES
a4mAppsDir=Users/frontrow/Applications
a4mLibrDir=Users/frontrow/Library
a4mXAppDir=XBMC.app/Contents/Resources/XBMC
a4mXLibDir=Application\ Support/XBMC
### CHECK VOLUME READ/WRITE SETTINGS
echo "[ATV1] Verifying that / is writable" & sleep 1
if mount | grep ' on / ' | grep -q 'read-only'; then
	echo "   [*] Re-mounting / as writable" & sleep 1
	sleep 1
	/sbin/mount -uw /
else
	echo "   [*] / is already writable" & sleep 1
fi
if [ ! -f /.readwrite ]; then
	echo "   [*] Creating /.readwrite for mount automation" & sleep 1
	touch /.readwrite
fi
### FIND AND LINK ADD-ON WEB INTERFACES
a4mFind=$(ls /$a4mLibrDir/"$a4mXLibDir"/addons/webinterface.* 2> /dev/null | wc -l | awk '{print $1}')
if [ "$a4mFind" != "0" ] ; then
	a4mWIntDir=( `ls /$a4mLibrDir/"$a4mXLibDir"/addons/ | grep "webinterface\." | awk -F'.' '{ print $2}'` )
	for a4mDir in "${a4mWIntDir[@]}"
	do
		echo "[XBMC] Checking existance of $a4mDir in Default Web Interface directory" & sleep 1
		if [ -d /$a4mAppsDir/$a4mXAppDir/addons/webinterface.default/$a4mDir ]; then
			if [ -h /$a4mAppsDir/$a4mXAppDir/addons/webinterface.default/$a4mDir ]; then
				echo "   [*] $a4mDir already linked to Default Web Interface directory" & sleep 1
			else
				echo "   [*] $a4mDir already exists in Default Web Interface directory" & sleep 1
			fi
		else
			echo "   [*] $a4mDir not found in Default Web Interface directory" & sleep 1
			if [ -d /$a4mLibrDir/"$a4mXLibDir"/addons/webinterface.$a4mDir ]; then
				echo "[XBMC] $a4mDir found in Library Add-ons directory" & sleep 1
				echo "   [*] Linking $a4mDir to Default Web Interface directory" & sleep 1
				ln -s /$a4mLibrDir/"$a4mXLibDir"/addons/webinterface.$a4mDir /$a4mAppsDir/$a4mXAppDir/addons/webinterface.default/$a4mDir
			fi
		fi
	done
	printf "\n----------------------------------------\n\n"
	echo "   [*] Visit each Web Interface seperately by visiting for example:"
	echo
	for a4mDir in "${a4mWIntDir[@]}"
	do
		echo "           eg. http://$HOSTNAME:8080/$a4mDir"
	done
else
	echo "[XBMC] No add-on Web Interfaces found in default Library location" & sleep 1
fi
printf "\n============================================================\n\n"